package com.seeyon.apps.receiveWen.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seeyon.apps.govdoc.manager.GovdocRestManager;
import com.seeyon.apps.receiveWen.util.RestWebServiceClient;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataDAO;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.content.mainbody.MainbodyManager;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.taglibs.functions.Functions;
import com.seeyon.ctp.organization.bo.V3xOrgAccount;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgEntity;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.AccountManager;
import com.seeyon.ctp.organization.manager.DepartmentManager;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.selectorg.vos.OrgAccount;
import com.seeyon.ctp.rest.vo.*;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.Inject;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.v3x.edoc.domain.EdocSummary;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ReceiveWenManagerImpl implements ReceiveWenManager {
    private static final Logger log = Logger.getLogger(ReceiveWenManagerImpl.class);


    @Inject
    private FormApi4Cap4 formApi4Cap4;
    @Inject
    private CAP4FormManager cap4FormManager;
    @Inject
    private AttachmentManager attachmentManager;
    @Inject
    private CAP4FormDataDAO cap4FormDataDAO;
    @Inject
    private EnumManager enumManagerNew;
    @Inject
    private MainbodyManager mainbodyManager;
    @Inject
    private OrgManager orgManager;
    @Inject
    private AccountManager accountManager;
    @Inject
    private DepartmentManager departmentManager;
    @Inject
    private GovdocRestManager govdocRestManager;

    private static final String yuebanFlow = AppContext.getSystemProperty("receiveWen.yuebanFlow");

    public Map<String, Object> send(Map<String, Object> params) {
        log.info("------开始处理接收文单：" + JSONUtil.toJSONString(params));
        Map<String, Object> result = new HashMap<>();
        User user = AppContext.getCurrentUser();
        /* 拼接收文单数据 */

        // 设置 formFieldDataList
        List<FormFieldDataVO> formFieldDataList = new ArrayList<>();
        ImportGovdocDataVO importGovdocDataVO = new ImportGovdocDataVO();
        
        // 设置 sendUnit
        String sendUnitCode = ParamUtil.getString(params, "sendUnit","");
        if (Strings.isNotEmpty(sendUnitCode)){
            UnitVO sendUnit = new UnitVO();
            Long sendUnitId = getAccountId(sendUnitCode);
            if (sendUnitId != null) {
                sendUnit.setUnitName(Functions.showOrgAccountName(sendUnitId));
                sendUnit.setUnitType("Account");
            } else {
                sendUnitId = getDepartmentId(sendUnitCode);
                if (sendUnitId != null) {
                    sendUnit.setUnitName(Functions.showDepartmentName(sendUnitId));
                    sendUnit.setUnitType("Department");
                }
            }
            if (sendUnitId != null) {
                sendUnit.setUnitId(sendUnitId);
                importGovdocDataVO.setSendUnit(sendUnit);
                String sendUnitStr = sendUnit.getUnitName() + "hiddenValue" + sendUnit.getUnitType() + "|" +sendUnitId.toString();
                FormFieldDataVO sendUnitFieldData = new FormFieldDataVO("send_unit", sendUnitStr);
                formFieldDataList.add(sendUnitFieldData);
            }
        }

        // 设置 receiveUnit
        String receiveUnitCode = ParamUtil.getString(params, "receiveUnit","");
        if (Strings.isNotEmpty(receiveUnitCode)){
            UnitVO receiveUnit = new UnitVO();
            Long receiveUnitId = getAccountId(receiveUnitCode);
            if (receiveUnitId != null) {
                receiveUnit.setUnitType("Account");
            } else {
                receiveUnitId = getDepartmentId(receiveUnitCode);
                if (receiveUnitId != null) {
                    receiveUnit.setUnitType("Department");
                }
            }
            if (receiveUnitId != null) {
                receiveUnit.setUnitId(receiveUnitId);
                importGovdocDataVO.setReceiveUnit(receiveUnit);
            }
        }

        // 设置 summaryData
        SummaryDataVO summaryData = new SummaryDataVO();
        summaryData.setTemplateModuleType(402); // 402 表单公文-收文
        summaryData.setSubject(ParamUtil.getString(params, "subject","文件阅办卡"));
        summaryData.setCreateUserId(AppContext.currentUserId()); // 替换为实际创建用户ID
        summaryData.setDeadline(0L); // 例如：60分钟
        summaryData.setTemplateCode(yuebanFlow); // 替换为实际模板编号
        summaryData.setKeywords("");
        importGovdocDataVO.setSummaryData(summaryData);
        
        // 设置 attachments
        List<GovdocAttachmentDataVO> attachments = new ArrayList<>();
        
        // 设置 attachments
        Object relatedAttachments = params.get("relatedAttachments");
        if (relatedAttachments instanceof List) {
            List<String> relatedAttachmentsList = (List<String>) relatedAttachments;
            if(relatedAttachmentsList != null && relatedAttachmentsList.size()>0) {
                for (String attachmentId : relatedAttachmentsList) {
                    GovdocAttachmentDataVO attachment = new GovdocAttachmentDataVO();
                    attachment.setFileId(Long.valueOf(attachmentId));
                    attachment.setArea(0);//0标题区 1表单区 2附言区 3意见区
                    //attachment.setFormFieldName("field0017");
                    attachment.setSort(0); //排序
                    attachments.add(attachment);
                }
            }
        }
        importGovdocDataVO.setAttachments(attachments);

        ContentFileDataVO contentFileData = new ContentFileDataVO();
        String mainContentId = MapUtils.getString(params, "mainContentId", "");
        String mainContentType = MapUtils.getString(params, "mainContentType", "");
        if (Strings.isEmpty(mainContentId) || Strings.isEmpty(mainContentType)){
            result.put("code", "error");
            result.put("message", "缺少参数：mainContentId, mainContentType");
            return result;
        } else {
            contentFileData.setFileId(Long.valueOf(mainContentId));
            contentFileData.setContent(null);
            //type: 正文类型 有如下：
            //HTML,10;
            //OfficeWord,41;
            //OfficeExcel,42;
            //WpsWord,43;
            //WpsExcel,44;
            //Pdf,45;
            //Ofd,46;
            contentFileData.setType(Integer.valueOf(mainContentType));
        }
        importGovdocDataVO.setContentFileData(contentFileData);

        String fileDate = MapUtils.getString(params, "receiveTime", "");
        if (Strings.isNotBlank(fileDate)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = sdf.parse(fileDate);
                long timestamp = date.getTime(); // 转换为时间戳
                FormFieldDataVO signingDate = new FormFieldDataVO();
                signingDate.setElementCode("receipt_date");
                signingDate.setValue(String.valueOf(timestamp));
                formFieldDataList.add(signingDate);
            } catch (ParseException e1) {
                log.error("日期转换异常",e1);
            }
        }

        FormFieldDataVO subjectVO = new FormFieldDataVO();
        subjectVO.setElementCode("subject");
        subjectVO.setValue(MapUtils.getString(params, "subject"));
        formFieldDataList.add(subjectVO);

        importGovdocDataVO.setFormFieldDataList(formFieldDataList);
        String resourceId = MapUtils.getString(params, "resourceId");
        if (Strings.isNotBlank(resourceId)) {
            importGovdocDataVO.setResourceId(Long.valueOf(resourceId));
        } else {
            importGovdocDataVO.setResourceId(UUID.randomUUID().getMostSignificantBits());
        }

        String urgencyLevelCode = MapUtils.getString(params, "urgencyLevel","");
        if(Strings.isNotEmpty(urgencyLevelCode)){
            try {
                CtpEnumItem itemByCode = enumManagerNew.getItemByCode(urgencyLevelCode);
                if (itemByCode != null) {
                    FormFieldDataVO urgentFieldData = new FormFieldDataVO("urgent_level", itemByCode.getId().toString());
                    formFieldDataList.add(urgentFieldData);
                }
            } catch (BusinessException e) {
                log.error("获取紧急程度异常",e);
            }
        }

        log.info("【公文交换】requestBody:"+ JSON.toJSONString(importGovdocDataVO));

//        String resultString = "";
//        RestWebServiceClient rc = new RestWebServiceClient(AppContext.getCurrentUser().getLoginName());
//        try {
//            JSONObject requestBody = (JSONObject) JSON.toJSON(importGovdocDataVO);
//            resultString =  rc.importJsonGovdoc(requestBody);
//            log.info("【公文交换】发起result:"+resultString);
//            result.put("code", "success");
//        } catch (Exception e) {
//            log.info("【公文交换】发起公文失败："+e.getMessage(),e);
//            result.put("code", "error");
//            result.put("message", e.getMessage());
//        }


        // 使用fastjson转换
//        Object o = ParamUtil.mapToBean(requestBody, ImportGovdocDataVO.class, false);
//        ImportGovdocDataVO importGovdocDataVO = (ImportGovdocDataVO) o;
        try {
            EdocSummary summary = govdocRestManager.transImportGovdoc(importGovdocDataVO);
            if (summary != null) {
                result.put("code", "success");
            } else {
                result.put("code", "error");
                result.put("message", "发起公文失败");
            }
        } catch (BusinessException e) {
            log.error( "【公文交换】发起公文失败：" + e.getMessage(), e);
            result.put("code", "error");
            result.put("message", e.getMessage());
        }

        return result;
    }

    private Long getAccountId(String accountCode) {
        Long accountId = null;
        if (Strings.isNotBlank(accountCode)) {
            try {
                List<V3xOrgEntity> entity = orgManager.getEntity(V3xOrgAccount.class.getSimpleName(), "code", accountCode, null);
                if (entity != null && entity.size() > 0) {
                    accountId = entity.get(0).getId();
                }
            } catch (BusinessException e) {
                log.error("获取组织信息失败" + accountCode, e);
            }
        }
        return accountId;
    }

    private Long getDepartmentId(String departmentCode) {
        Long departmentId = null;
        if (Strings.isNotBlank(departmentCode)) {
            try {
                List<V3xOrgEntity> entity = orgManager.getEntity(V3xOrgDepartment.class.getSimpleName(), "code", departmentCode, null);
                if (entity != null && entity.size() > 0) {
                    departmentId = entity.get(0).getId();
                }
            } catch (BusinessException e) {
                log.error("获取组织信息失败" + departmentCode, e);
            }
        }
        return departmentId;
    }

    private Long getUnitId(String unitCode) {
        Long sendUnitId = null;
        if (Strings.isNotBlank(unitCode)) {
            try {
                List<V3xOrgEntity> code = orgManager.getEntity(V3xOrgAccount.class.getSimpleName(), "code", unitCode, null);
                if (code != null && code.size() > 0) {
                    sendUnitId = code.get(0).getId();
                } else {
                    List<V3xOrgEntity> name = orgManager.getEntity(V3xOrgDepartment.class.getSimpleName(), "code", unitCode, null);
                    if (name != null && name.size() > 0) {
                        sendUnitId = name.get(0).getId();
                    }
                }

            } catch (BusinessException e) {
                log.error("获取组织信息失败" + unitCode, e);
            }
        }
        return sendUnitId;
    }

    private Long getMemberId(String memberCode) {
        Long memberId = null;
        if (Strings.isNotBlank(memberCode)) {
            try {
                List<V3xOrgEntity> entity = orgManager.getEntity(V3xOrgMember.class.getSimpleName(), "code", memberCode, null);
                if (entity != null && entity.size() > 0) {
                    memberId = entity.get(0).getId();
                }
            } catch (BusinessException e) {
                log.error("获取组织信息失败" + memberCode, e);
            }
        }
        return memberId;
    }
}